<#include "ftl/common.ftl">
<!DOCTYPE html>
<html lang="zh-Hans">

<head>
  <title></title>
  <#include "ftl/generate/head.ftl">
  <style>
    #app {
      margin: 0 auto;
      background-color: #f5f5f5;
    }
  </style>
</head>

<body style="background-color: #f5f5f5;">

<div id="app" style="opacity: 0" :style="{opacity: '1', width: isMobile ? '100%' : appBoxWidth, backgroundColor: '#fff', minHeight: '100vh'}">
  <#include "ftl/generate/template.ftl">

  <el-dialog title="查看已保存的数据" :visible.sync="externalVisible" width="800px" :fullscreen="isMobile">
    <div>
      <p style="font-size: 0.8rem;color: #999999;">仅展示最近的五条数据</p>
      <el-timeline v-if="externalSavedList.length > 0" :style="{paddingLeft:isMobile?'0':null}">
        <#-- 只展示前五条 -->
        <template v-for="(data,idx) of externalSavedList">
          <el-timeline-item v-if="idx < 5" :key="idx" :timestamp="data.updateTime" placement="top">
            <el-card>
              <template v-if="idx===0">
                <el-link v-if="isEditing(data.dataId)" @click="externalVisible=false">正在编辑</el-link>
                <el-link v-else type="primary" @click="jumpTo(data.dataId)">点击编辑</el-link>
                <span> | </span>
              </template>
              <el-link v-if="isReusing(data.dataId)" @click="externalVisible=false">正在复用</el-link>
              <el-link v-else type="primary" @click="jumpTo(data.dataId, true)">复用</el-link>
              <p>保存时间：<br>{{data.updateTime}}</p>
              <p style="text-align: right;margin: 0;">
                <el-link type="primary" @click="handleRemove(data.dataId)">删除</el-link>
              </p>
            </el-card>
          </el-timeline-item>
        </template>
      </el-timeline>
      <h3 v-else style="text-align: center;margin-top: 50px;">你还未保存任何数据</h3>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="!isMobile" type="primary" plain @click="jumpTo()">提交新数据</el-button>
      <el-button type="primary" @click="externalVisible = false" :style="{width:isMobile?'100%':null}">确 定</el-button>
      <el-button v-if="isMobile" type="primary" plain @click="jumpTo()" style="width:100%;margin: 8px 0 0 0;">提交新数据</el-button>
    </div>
  </el-dialog>

</div>

<#include "ftl/generate/importJmForm.ftl">

<script>

  // 从配置里读取主题颜色
  window['THEME_COLOR'] = '${themeColor}'
  // 从配置里读取上传方式
  window['UPLOAD_TYPE'] = '${uploadType}'

  // 外部链接使用模拟 Token、无messageId
  var token = '${mockToken}', messageId = ''

  var innerRequest = true, innerDialog = false, skip = true, disableScroll = false

  var baseURL = '${baseURL}'
  Vue.ls.set(constant.BASE_URL, baseURL)
  Vue.ls.set(constant.ACCESS_TOKEN, token)

  var isExternal = true
  store.commit('TOGGLE_IS_EXTERNAL', isExternal)

  window['__authUserInfo'] = {}

  // 外部页面专用的 Vue混入
  var ExternalMixins = {
    data: function () {
      return {
        isExternal: isExternal,
        externalSavedList: [],
        externalVisible: false,
        initialModels: '',
        // 页面宽度，会根据表单配置动态变更
        appBoxWidth: '1000px',
      }
    },
    mounted: function () {
      this.externalSavedList = this.getExternalSaved()
      var _this = this
      this.$nextTick(function () {
        _this.initialModels = JSON.stringify(_this.$refs['generateForm'].models)
      })
      this.appBoxWidth = this.jsonData.config.dialogOptions.width + 'px'
    },
    methods: {

      isEditing: function (dataId) {
        return dataId === this.dataId && this.action !== 'add'
      },

      isReusing: function (dataId) {
        return dataId === this.dataId && this.action === 'add'
      },

      handleViewExternalSaved: function () {
        this.externalVisible = true
      },

      // 判断数据是否更改
      dataIsChanged: function () {
        try {
          var models = this.$refs['generateForm'].models
          var jsonModels = JSON.stringify(models)
          if (jsonModels === this.initialModels || jsonModels === JSON.stringify(this.editData)) {
            return false
          }
          var changed = false
          for (var key in models) {
            if (models.hasOwnProperty(key)) {
              if (models[key] != null && models[key] !== '') {
                changed = true
                break
              }
            }
          }
          return changed
        } catch (e) {
          console.error(e)
        }
        return true
      },
      // 跳转至新页面
      jumpTo: function (dataId, reuse) {
        var url = baseURL + '/desform/ext/' + this.desformCode
        if (dataId) {
          if (reuse) {
            url += '?reuseId=' + dataId
          } else {
            url += '/' + dataId
          }
        }
        if (this.dataIsChanged()) {
          this.$confirm('确定放弃当前尚未保存的数据吗？', '提示', {
            type: 'warning'
          }).then(function () {
            window.location.href = url
          }).catch(function () {
          })
        } else {
          window.location.href = url
        }
      },

      /** 删除一条数据（只删缓存） */
      handleRemove: function (dataId) {
        var _this = this
        if (this.isEditing(dataId)) {
          this.$message.warning('当前正在编辑，无法删除')
          return
        }
        if (this.isReusing(dataId)) {
          this.$message.warning('当前正在复用，无法删除')
          return
        }
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning'
        }).then(function () {
          var dataList = _this.getExternalSaved()

          for (var i in dataList) {
            if (!dataList.hasOwnProperty(i)) {
              continue
            }
            if (dataList[i].dataId === dataId) {
              dataList.splice(i, 1)
              break
            }
          }
          _this.saveExternalSaved(dataList)
          _this.$message.success('删除成功')
        }).catch(function () {
        })
      },

      getExternalSavedKey: function () {
        return 'EXTERNAL_SAVED_' + this.desformCode
      },
      // 从缓存中取出已保存的数据
      getExternalSaved: function () {
        return this.$ls.get(this.getExternalSavedKey()) || []
      },
      // 向缓存中保存数据，自动去重
      setExternalSaved: function (dataId) {
        var dataList = this.getExternalSaved() || []
        for (var idx in dataList) {
          if (dataList.hasOwnProperty(idx)) {
            var data = dataList[idx]
            if (data.dataId === dataId) {
              dataList.splice(idx, 1)
              break
            }
          }
        }
        // 最新的数据永远放到第一条
        dataList.splice(0, 0, { dataId: dataId, updateTime: moment().format('YYYY年MM月DD日 HH时mm分ss秒') })
        this.saveExternalSaved(dataList)
      },

      saveExternalSaved: function (dataList) {
        this.$ls.set(this.getExternalSavedKey(), dataList)
        this.externalSavedList = this.getExternalSaved()
      },

    }
  }


</script>

<#include "ftl/generate/script.ftl" >

</body>

</html>